package java7;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Phaser包含了CyclicBarrier和CountDownLatch的相关功能
 *
 * @author user
 */
public class J9 {
    public static void main(String[] args) throws Exception {
        Phaser phaser = new Phaser(1);//此处可使用CountDownLatch(1)
        ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        for (int i = 0; i < 3; i++) {
            exec.submit(new MyCall((char) (97 + i), phaser));
        }
        TimeUnit.SECONDS.sleep(3L);
        phaser.arrive();//此处可使用latch.countDown()
        System.out.println("begin.....");

    }

    static class MyCall implements Callable<Integer> {
        private char c;
        private Phaser phaser;

        public MyCall(char c, Phaser phaser) {
            this.c = c;
            this.phaser = phaser;
        }

        @Override
        public Integer call() throws Exception {
            phaser.awaitAdvance(phaser.getPhase()); //此处可使用latch.await()
            for (int i = 0; i < 100; i++) {
                System.out.print(c + " ");
                if (i % 10 == 9) {
                    System.out.println();
                }
            }
            return 0;
        }
    }

}
